<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 保持原有的搜索表单结构 -->
      <el-form-item label="学生姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="班级" prop="personClass">
        <el-input
          v-model="queryParams.classes"
          placeholder="请输入班级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="学号" prop="studentId">
        <el-input
          v-model="queryParams.studentId"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="签到日期" prop="recordDate">
        <el-date-picker clearable
          v-model="queryParams.recordDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择签到日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="签到位置" prop="deviceLocation">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入签到位置"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['attendance:attendance:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['attendance:attendance:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['attendance:attendance:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['attendance:attendance:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="学生姓名" align="center" prop="name" />
      <el-table-column label="班级" align="center" prop="classes" />
  <el-table-column label="学生照片" align="center" prop="photo" width="100">
    <template slot-scope="scope">
      <image-preview
        v-if="scope.row.photo"
        :src="getFullImageUrl(scope.row.photo)"
        :width="50"
        :height="50"/>
    </template>
  </el-table-column>
      <el-table-column label="学生学号" align="center" prop="studentId" />
      <el-table-column label="签到日期" align="center" prop="recordDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="早上签到" align="center" prop="morningSignIn">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sign_in_status" :value="scope.row.morningSignIn"/>
        </template>
      </el-table-column>
      <el-table-column label="早上签到时间" align="center" prop="morningSignInTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.morningSignInTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="中午签退" align="center" prop="noonSignOut">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sign_out_status" :value="scope.row.noonSignOut"/>
        </template>
      </el-table-column>
      <el-table-column label="中午签退时间" align="center" prop="noonSignOutTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.noonSignOutTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下午签到" align="center" prop="afternoonSignIn">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sign_in_status" :value="scope.row.afternoonSignIn"/>
        </template>
      </el-table-column>
      <el-table-column label="下午签到时间" align="center" prop="afternoonSignInTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.afternoonSignInTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="晚上签退" align="center" prop="eveningSignOut">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sign_out_status" :value="scope.row.eveningSignOut"/>
        </template>
      </el-table-column>
      <el-table-column label="晚上签退时间" align="center" prop="eveningSignOutTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.eveningSignOutTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签到位置" align="center" prop="location" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['attendance:attendance:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['attendance:attendance:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

       <!-- 修改后的对话框 -->
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
  >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20"> <!-- 使用栅格布局 -->
        <!-- 左列 -->
        <el-col :span="12">
        <!-- 人员选择下拉框 -->
        <el-form-item label="选择学生" prop="pid">
          <el-select
            v-model="form.pid"
            placeholder="请选择学生"
            filterable
            clearable
            @change="handlePersonChange">
            <el-option
              v-for="person in personList"
              :key="person.pid"
              :label="person.name + ' (' + person.studentId + ')'"
              :value="person.pid">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 设备选择下拉框 -->
        <el-form-item label="设备SN" prop="sn">
          <el-select
            v-model="form.sn"
            placeholder="请选择设备"
            filterable
            clearable>
            <el-option
              v-for="device in deviceList"
              :key="device.sn"
              :label="device.sn"
              :value="device.sn">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 人员信息显示 -->
        <el-card shadow="never">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>学生姓名:</label>
                <span>{{ personInfo.name }}</span>
              </div>
              <div class="info-item">
                <label>班级:</label>
                <span>{{ personInfo.classes }}</span>
              </div>
              <div class="info-item">
                <label>学号:</label>
                <span>{{ personInfo.studentId }}</span>
              </div>
            </el-col>
            <el-col :span="12" class="text-center">
  <image-preview
    v-if="personInfo.photo"
    :src="personInfo.photo"
    :width="100"
    :height="100"
    class="preview-image"/>
            </el-col>
          </el-row>
        </el-card>
        <el-form-item label="签到日期" prop="recordDate">
          <el-date-picker clearable
            v-model="form.recordDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择签到日期">
          </el-date-picker>
        </el-form-item>
<!-- 早上签到 -->
<el-form-item label="早上签到" prop="morningSignIn">
  <el-radio-group v-model="form.morningSignIn">
    <el-radio
      v-for="dict in dict.type.sign_in_status"
      :key="dict.value"
      :label="parseInt(dict.value)"
      style="margin-right: 15px"
    >{{ dict.label }}</el-radio>
  </el-radio-group>
</el-form-item>
        <el-form-item label="早上签到时间" prop="morningSignInTime">
          <el-date-picker
            v-model="form.morningSignInTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择早上签到时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
                </el-col>
                <!-- 右列 -->
        <el-col :span="12">

<!-- 中午签退 -->
<el-form-item label="中午签退" prop="noonSignOut">
  <el-radio-group v-model="form.noonSignOut">
    <el-radio
      v-for="dict in dict.type.sign_out_status"
      :key="dict.value"
      :label="parseInt(dict.value)"
      style="margin-right: 15px"
    >{{ dict.label }}</el-radio>
  </el-radio-group>
</el-form-item>
          <el-form-item label="中午签退时间" prop="noonSignOutTime">
          <el-date-picker
            v-model="form.noonSignOutTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择中午签退时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>

<!-- 下午签到 -->
<el-form-item label="下午签到" prop="afternoonSignIn">
  <el-radio-group v-model="form.afternoonSignIn">
    <el-radio
      v-for="dict in dict.type.sign_in_status"
      :key="dict.value"
      :label="parseInt(dict.value)"
      style="margin-right: 15px"
    >{{ dict.label }}</el-radio>
  </el-radio-group>
</el-form-item>

        <el-form-item label="下午签到时间" prop="afternoonSignInTime">
          <el-date-picker
            v-model="form.afternoonSignInTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择下午签到时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>

<!-- 晚上签退 -->
<el-form-item label="晚上签退" prop="eveningSignOut">
  <el-radio-group v-model="form.eveningSignOut">
    <el-radio
      v-for="dict in dict.type.sign_out_status"
      :key="dict.value"
      :label="parseInt(dict.value)"
      style="margin-right: 15px"
    >{{ dict.label }}</el-radio>
  </el-radio-group>
</el-form-item>

        <el-form-item label="晚上签退时间" prop="eveningSignOutTime">
          <el-date-picker
            v-model="form.eveningSignOutTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择晚上签退时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
       </el-col>
      </el-row>
    </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttendance, getAttendance, delAttendance, addAttendance, updateAttendance } from "@/api/student/attendance/attendance";
import { listPerson, getPerson, listAllPerson } from "@/api/student/person/person";
import { listDevice, getDevice } from "@/api/student/device/device";
import { getFullImageUrl } from '@/utils/imageUtils';


export default {
  name: "Attendance",
  dicts: ['sign_in_status', 'sign_out_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生签到记录表格数据
      attendanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,        // 新增：学生姓名查询条件
        classes: null,     // 新增：班级查询条件
        studentId: null,   // 新增：学号查询条件
        recordDate: null,
        location: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        pid: [
          { required: true, message: "学生pid 不能为空", trigger: "change" }
        ],
        recordDate: [
          { required: true, message: "签到日期不能为空", trigger: "blur" }
        ],
      },
            // 新增数据
      personList: [],       // 人员列表
      deviceList: [],       // 设备列表
      personInfo: {},       // 当前选中人员信息
    };
  },
  created() {
    this.getList();
    this.getPersonList();
    this.getDeviceList();
  },
  methods: {
    // 新增方法
   getFullImageUrl(path) {
      if (!path) return '';
      // 如果已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      // 特殊处理，为 `data/facelib` 路径添加特定前缀
      if (path.startsWith('data/facelib')) {
        return 'http://wechatfuwu.natapp1.cc/' + path;
      }
      // 一般情况：使用环境变量前缀（如果以后需要）
      // 注意：这里我们直接返回路径，因为环境变量前缀在开发环境为空，生产环境为完整URL
      // 但是，我们已经在生产环境的环境变量中设置了基础URL，所以这里可以加上
      const baseUrl = process.env.VUE_APP_CAMERA_SERVER_BASE_URL || '';
      return baseUrl + path;
    },
    /** 获取所有人员 */
    getPersonList() {
      // 不分页获取所有人员
      listPerson({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.personList = response.rows;
      });
    },

    /** 获取所有设备 */
    getDeviceList() {
      listDevice({ pageNum: 1, pageSize: 100 }).then(response => {
        this.deviceList = response.rows;
      });
    },

    /** 获取图片服务器基础URL */
    getCameraBaseUrl() {
      this.cameraServerBaseUrl = process.env.VUE_APP_CAMERA_SERVER_BASE_URL;
    },


    /** 当选择人员发生变化 */
    handlePersonChange(pid) {
      this.personInfo = {};

      if (!pid) return;

      const selectedPerson = this.personList.find(p => p.pid === pid);

      if (selectedPerson) {
        this.personInfo = {
          name: selectedPerson.name,
          classes: selectedPerson.classes,
          studentId: selectedPerson.studentId,
          photo: getFullImageUrl(selectedPerson.photo) // 使用工具函数处理照片路径
        };
      } else {
        getPerson(pid).then(response => {
          if (response.data) {
            this.personInfo = {
              name: response.data.name,
              classes: response.data.classes,
              studentId: response.data.studentId,
              photo: getFullImageUrl(response.data.photo) // 使用工具函数处理照片路径
            };
          }
        });
      }
    },
 /** 查询学生签到记录列表 */
    getList() {
      this.loading = true;

      // 构造查询参数（为关联表添加后缀）
  const params = {
    name: this.queryParams.name,
    classes: this.queryParams.classes,
    studentId: this.queryParams.studentId,
    location: this.queryParams.location,
    pageNum: this.queryParams.pageNum,
    pageSize: this.queryParams.pageSize,
  };

    // 处理日期格式
  if (this.queryParams.recordDate) {
    params.recordDate = this.parseTime(this.queryParams.recordDate, '{y}-{m}-{d}');
  }

      listAttendance(params).then(response => {
        this.attendanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pid: null,
        recordDate: null,
        morningSignIn: null,
        morningSignInTime: null,
        noonSignOut: null,
        noonSignOutTime: null,
        afternoonSignIn: null,
        afternoonSignInTime: null,
        eveningSignOut: null,
        eveningSignOutTime: null,
        location: null,
        sn: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
  /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        personName: null,
        personClass: null,
        studentId: null,
        recordDate: null,
        deviceLocation: null,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
     /** 打开新增对话框 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生签到记录";

      // 重置人员信息
      this.personInfo = {};
    },

    /** 打开编辑对话框 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAttendance(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生签到记录";

        // 如果已有人员PID，加载人员信息
        if (this.form.pid) {
          this.handlePersonChange(this.form.pid);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAttendance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttendance(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学生签到记录编号为"' + ids + '"的数据项？').then(function() {
        return delAttendance(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('student/attendance/attendance/export', {
        ...this.queryParams
      }, `attendance_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.info-item {
  margin-bottom: 10px;
  font-size: 14px;
}
.info-item label {
  display: inline-block;
  width: 60px;
  font-weight: bold;
  color: #606266;
}
.preview-image {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>
